.PHONY: build test clean install run help lint fmt deps

# 变量定义
BINARY_NAME=collector
BUILD_DIR=build
GO_FILES=$(shell find . -name "*.go" -type f)
VERSION="1.0.0"
GIT_COMMIT="unknow"
BUILD_TIME=$(shell date +%Y-%m-%dT%H:%M:%S%z)
LDFLAGS=-X github.com/CIPFZ/collector/pkg/version.Version=${VERSION} \
        -X github.com/CIPFZ/collector/pkg/version.GitCommit=${GIT_COMMIT} \
        -X github.com/CIPFZ/collector/pkg/version.BuildTime=${BUILD_TIME}

# 默认目标
all: build

# 构建
build:
	@echo "Building $(BINARY_NAME)..."
	@mkdir -p $(BUILD_DIR)
	CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME) main.go

# 多平台构建
build-all:
	@echo "Building for multiple platforms..."
	@mkdir -p $(BUILD_DIR)
	GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 main.go
	GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe main.go
	GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64 main.go
	GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 main.go

# 测试
test:
	@echo "Running tests..."
	go test -v ./...

# 代码覆盖率
test-coverage:
	@echo "Running tests with coverage..."
	go test -v -coverprofile=coverage.out ./...
	go tool cover -html=coverage.out -o coverage.html

# 代码检查
lint:
	@echo "Running linter..."
	golangci-lint run

# 格式化代码
fmt:
	@echo "Formatting code..."
	go fmt ./...

# 安装依赖
deps:
	@echo "Installing dependencies..."
	go mod download
	go mod tidy

# 运行
run:
	go run -ldflags "$(LDFLAGS)" main.go

# 初始化配置
init-config:
	@echo "Initializing configuration..."
	@mkdir -p configs
	@if [ ! -f configs/default.yaml ]; then \
		echo "Creating default configuration..."; \
	fi

# 清理
clean:
	@echo "Cleaning up..."
	rm -rf $(BUILD_DIR)
	rm -f coverage.out coverage.html

# 安装到系统
install: build
	@echo "Installing $(BINARY_NAME)..."
	sudo cp $(BUILD_DIR)/$(BINARY_NAME) /usr/local/bin/

# 卸载
uninstall:
	@echo "Uninstalling $(BINARY_NAME)..."
	sudo rm -f /usr/local/bin/$(BINARY_NAME)

# 开发模式运行
dev:
	go run -ldflags "$(LDFLAGS)" main.go --debug

# 帮助
help:
	@echo "Available targets:"
	@echo "  build         - Build the application"
	@echo "  build-all     - Build for multiple platforms"
	@echo "  test          - Run tests"
	@echo "  test-coverage - Run tests with coverage report"
	@echo "  lint          - Run code linter"
	@echo "  fmt           - Format code"
	@echo "  deps          - Install dependencies"
	@echo "  run           - Run the application"
	@echo "  dev           - Run in development mode"
	@echo "  init-config   - Initialize configuration files"
	@echo "  clean         - Clean build artifacts"
	@echo "  install       - Install to system"
	@echo "  uninstall     - Uninstall from system"
	@echo "  help          - Show this help"